#include "MLImportance.hpp"
#include <cmath>

#define RED_FACTOR    0.299
#define GREEN_FACTOR  0.587
#define BLUE_FACTOR   0.114

MLImportance::MLImportance(int iWidth, int iHeight)
{
	m_iWidth = iWidth;
	m_iHeight = iHeight;

	m_pImportanceTable = new unsigned[m_iWidth * m_iHeight];
}

unsigned MLImportance::getImportanceAt(int x, int y)
{
	//if(x >= 0 && y >= 0 && x < m_iWidth && y < m_iHeight)  //test already in sampler
	
	return m_pImportanceTable[y*m_iWidth + x];
}

bool MLImportance::buildMap(BYTE *pImagePixels, int iPitch)
{
	bool bSuccess = false;
	BYTE* pOffset = pImagePixels;
	BYTE* pLocalOffset = 0;
	unsigned size = sizeof(BYTE);
	unsigned iCounter = 0;
	unsigned iLine = 0;

	for(int i = 0; i < m_iWidth*m_iHeight; ++i)
	{
		pLocalOffset = pOffset;

		char _r = *pLocalOffset;
		pLocalOffset += size;
		char _g = *pLocalOffset;
		pLocalOffset += size;
		char _b = *pLocalOffset;
		pLocalOffset += size;
		char _mantiss = *pLocalOffset;
		
		double fullR, fullG, fullB;

		fullR = _r * pow(2.0, _mantiss);
		fullG = _g * pow(2.0, _mantiss);
		fullB = _b * pow(2.0, _mantiss);

		double importance = (fullR * RED_FACTOR) + (fullG * GREEN_FACTOR) + (fullB * BLUE_FACTOR);

		m_pImportanceTable[iLine*m_iWidth + iCounter] = importance;
		
		iCounter +=1;
		if(iCounter == m_iWidth)
		{
			pOffset += iPitch;
			iCounter = 0;
			++iLine;
		}
	}


	return bSuccess;
}

//EOF
